<template>
	<div>
		<el-dialog title="文件预览" :visible.sync="dialogVisible" append-to-body>
			<img width="100%" :src="dialogImageUrl" alt="" />
		</el-dialog>
	</div>
</template>
<script>
import { getFileName, isImg, isPdf, getHttpURL, download } from '@/utils/fileUtils'
export default {
	data() {
		return {
			vHtml: '',
			dialogImageUrl: '',
			dialogVisible: false,
			// 文件类型
			file_type: '',
			functionMap: {},
		}
	},
	created() {
		this.functionMap = {
			img: this.openImg,
			pdf: this.openPdf,
		}
	},
	methods: {
		open(f) {
			let file = this.getFile(f)
			if (isImg(file.url)) {
				this.functionMap['img'](file)
			} else if (isPdf(file.url)) {
				this.functionMap['pdf'](file)
			} else {
				download(file.url)
			}
		},
		// 如果file是字符串，则转为file对象
		getFile(file) {
			if (typeof file === 'string') {
				file = {
					name: getFileName(file.url),
					url: file,
				}
			} else {
				if (!file.name) {
					file.name = getFileName(file.url)
				}
			}
			file.url = getHttpURL(file.url)
			return file
		},
		openPdf(row) {
			const width = 1000
			const height = 800
			const top = (window.screen.availHeight - height) / 2
			const left = (window.screen.availWidth - width) / 2
			window.open(getHttpURL(row.url), '', 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left)
		},
		openImg(row) {
			this.dialogImageUrl = getHttpURL(row.url)
			this.dialogVisible = true
		},
	},
}
</script>
